package com.weixu.fileconver.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * LibreOffice配置类
 * @Author weixu
 * @Date 2025/8/29
 */
@Configuration
@Data
@ConfigurationProperties(prefix = "libreoffice")
public class LibreOfficeConfig {
    
    /**
     * LibreOffice安装路径
     */
    private String home;
    
    /**
     * LibreOffice端口
     */
    private Integer port = 8100;
    
    /**
     * 连接超时时间（毫秒）
     */
    private Long timeout = 30000L;
    
    /**
     * 最大任务数
     */
    private Integer maxTasksPerProcess = 200;
    
    /**
     * 任务执行超时时间（毫秒）
     */
    private Long taskExecutionTimeout = 120000L;
    
    /**
     * 任务队列超时时间（毫秒）
     */
    private Long taskQueueTimeout = 30000L;
    
    /**
     * 获取LibreOffice可执行文件路径
     * @return LibreOffice可执行文件路径
     */
    public String getExecutablePath() {
        if (home == null || home.trim().isEmpty()) {
            // 自动检测LibreOffice安装路径
            return detectLibreOfficePath();
        }
        
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")) {
            return home + "\\program\\soffice.exe";
        } else {
            return home + "/program/soffice";
        }
    }
    
    /**
     * 自动检测LibreOffice安装路径
     * @return LibreOffice安装路径
     */
    private String detectLibreOfficePath() {
        String os = System.getProperty("os.name").toLowerCase();
        
        if (os.contains("win")) {
            // Windows常见安装路径
            String[] windowsPaths = {
                "C:\\Program Files\\LibreOffice\\program\\soffice.exe",
                "C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe",
                "D:\\Program Files\\LibreOffice\\program\\soffice.exe",
                "D:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe"
            };
            
            for (String path : windowsPaths) {
                if (new java.io.File(path).exists()) {
                    return path;
                }
            }
        } else {
            // Linux常见安装路径
            String[] linuxPaths = {
                "/usr/bin/libreoffice",
                "/usr/bin/soffice",
                "/opt/libreoffice/program/soffice",
                "/usr/lib/libreoffice/program/soffice"
            };
            
            for (String path : linuxPaths) {
                if (new java.io.File(path).exists()) {
                    return path;
                }
            }
        }
        
        throw new RuntimeException("无法找到LibreOffice安装路径，请在配置文件中指定libreoffice.home");
    }
}